// 严格模式开发
'use strict';

// 记录打开页面的对象
window['pages'] = [];

// 页面作用域
window.scope = {};

// 公共lib配置
require.config({
    baseUrl: './node_modules/',
    waitSeconds: 0,
    map: {
        '*': {
            css: 'require-css/css'
        }
    },
    shim: {
        bootstrap: {
            deps: ['jquery']
        },
        bootstrapTable: {
            deps: [
                'jquery',
                'css!../node_modules/bootstrap-table/src/bootstrap-table'
            ]
        },
        bootstrapTableZh: {
            deps: ['bootstrapTable']
        },
        highcharts: {
            deps: [
                'jquery',
                'css!../node_modules/highcharts/css/highcharts'
            ],
            exports: 'Highcharts'
        },
        icheck: {
            deps: [
                'jquery',
                'css!../node_modules/icheck/skins/square/green'
            ]
        },
        toastr: {
            deps: ['css!../node_modules/toastr/build/toastr']
        },
        webuploader: {
            deps: ['css!../node_modules/webuploader/dist/webuploader']
        },
        ztree: {
            deps: [
                'jquery',
                'css!../node_modules/ztree/css/metroStyle/metroStyle'
            ]
        },
        pace: {
            deps: ['css!../node_modules/pace-progress/templates/pace-theme-minimal.tmpl']
        },
        slimscroll: {
            deps: ['jquery']
        },
        jstree: {
            deps: ['css!../node_modules/jstree/dist/themes/default/style.css']
        },
        fancybox: {
            deps: ['css!../node_modules/fancybox/dist/css/jquery.fancybox.css']
        }
    },
    paths: {
        jquery: 'jquery/dist/jquery',
        bootstrap: 'bootstrap/dist/js/bootstrap',
        underscore: 'underscore/underscore',
        backbone: 'backbone/backbone',
        backboneLocalstorage: 'backbone.localstorage/build/backbone.localStorage',
        text: 'requirejs-text/text',
        bootstrapSuggest: 'bootstrap-suggest-plugin/src/bootstrap-suggest',
        bootstrapTable: 'bootstrap-table/src/bootstrap-table',
        bootstrapTableZh: 'bootstrap-table/src/locale/bootstrap-table-zh-CN',
        echarts: 'echarts/dist/echarts',
        echartsMapChina: 'echarts/map/js/china',
        highcharts: 'highcharts/js/highcharts.src',
        icheck: 'icheck/icheck',
        '../jquery.validate': 'jquery-validation/dist/jquery.validate',
        jqueryValidationZh: 'jquery-validation/dist/localization/messages_zh',
        layer: 'layui-layer/src/layer',
        laydate: 'layui-laydate/src/laydate',
        toastr: 'toastr/toastr',
        webuploader: 'webuploader/dist/webuploader',
        ztree: 'ztree/js/jquery.ztree.all',
        md5: 'blueimp-md5/js/md5',
        metisMenu: 'metismenu/dist/metisMenu',
        slimscroll: 'jquery-slimscroll/jquery.slimscroll',
        jstree: 'jstree/dist/jstree',
        fancybox: 'fancybox/dist/js/jquery.fancybox',
        hplus: '../common/js/hplus',
        common: '../common/js/common'
    }
});

// 页面初始化
require(['jquery', 'bootstrap', 'metisMenu', 'slimscroll', 'layer'], function() {
    layer.config({
        path: './node_modules/layui-layer/src/'
    });
    require(['hplus']);
});

// 模拟路由
function router(param) { // pageName为moduleName，src完整路径，state页面执行状态
    var reqMoudelName = '../pages/' + param.pageName + '/' + param.pageName; // 匿名模块的模块名称，用于移除
    if (param.status !== 'init') {
        var cur = currentPage(reqMoudelName);
        if (cur && typeof cur.page[param.status] === 'function') {
            cur.page[param.status]();
        }
        if (param.status === 'in') { // 再次切进页面
            setTitle(param.pageName);
            setScope(cur.page);
        }
        if (param.status === 'destroy') { // 关闭页面
            destroyPage(reqMoudelName);
            cur && window.pages.splice(cur.index, 1);
        }
    } else { // 第一次进来
        loadHtml(reqMoudelName, param);
    }
}

// 初始化页面html
function loadHtml(reqMoudelName, param) {
    window.pageLoad = layer.load(2, { shade: [0.5, '#fff'] });
    require(['text!' + reqMoudelName + '.html'], function(text) {
        param.el.html(text);
        setTitle(param.pageName);
        loadPage(reqMoudelName, param.pageName);
    });
}

// 初始化页面js
function loadPage(reqMoudelName, pageName) {
    require([
        reqMoudelName, // 动态参数
        'css!' + reqMoudelName
    ], function(page) {
        layer.close(window.pageLoad);
        page = typeof page === 'object' ? page : {};
        window.pages.push({
            pageName: pageName,
            reqMoudelName: reqMoudelName,
            page: page
        });
        setScope(page);
        if (typeof page.init === "function") {
            page.init();
        }
    });
}

// 销毁页面
function destroyPage(reqMoudelName) {
    requirejs.undef(reqMoudelName); // 销毁模块 // 依赖的模块不销毁
    requirejs.undef('require-css/css!' + reqMoudelName); // 销毁css
    $('link[href*="' + reqMoudelName + '"]').remove();
}

// 获得当前页
function currentPage(name) {
    var index_;
    var page = window.pages.filter(function(item, index) {
        if (item.reqMoudelName === name || item.pageName === name) {
            index_ = index;
            return true;
        }
    });
    if (index_ === undefined || page.length !== 1 || !page[0] || !page[0].page) return;
    return {
        index: index_,
        page: page[0].page
    }
}

// 设置作用域
function setScope(exports) {
    window.scope = {};
    $.extend(window.scope, exports);
    delete window.scope.init;
    delete window.scope.in;
    delete window.scope.out;
    delete window.scope.destroy;
}

// 设置title
function setTitle(name) {
    var pageTitle = $('title').text().split('-')[0];
    if (pageTitle.indexOf('#') < 0) window.pageTitle = pageTitle;
    var title = $('.J_iframe #' + name).attr('name') || $('.J_iframe:visible .wrapper-content').attr('name');
    $('title').text(window.pageTitle + (title ? '-' + title : ''));
}

// ie title在加载flash时变成#
document.attachEvent && document.attachEvent('onpropertychange', function(evt) {
    evt = evt || window.event;
    if (evt.propertyName === 'title' && $('title').text().indexOf('#') >= 0) {
        setTimeout(function() {
            setTitle();
        });
    }
});